package com.ytjj.qmyx.mall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.constants.TokenConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.DynamicConstant;
import com.ytjj.qmyx.mall.constants.ExpireTimeConstant;
import com.ytjj.qmyx.mall.constants.IsCollectConstant;
import com.ytjj.qmyx.mall.constants.MyWalletConstant;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.mapper.CouponRecordsDao;
import com.ytjj.qmyx.mall.mapper.OrdersDao;
import com.ytjj.qmyx.mall.mapper.ProductDao;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.dto.OldForNewProductDto;
import com.ytjj.qmyx.mall.model.dto.RecordSubsidyDataDto;
import com.ytjj.qmyx.mall.model.dto.SignDto;
import com.ytjj.qmyx.mall.model.esmodel.RedEnvelopeDto;
import com.ytjj.qmyx.mall.model.esmodel.WalletSignDto;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.CommonService;
import com.ytjj.qmyx.mall.service.ProductService;
import com.ytjj.qmyx.mall.utils.DateUtils;
import com.ytjj.qmyx.mall.utils.FakeUserUtil;
import com.ytjj.qmyx.mall.utils.TipsUtil;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.model.UsersCouponDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动控制器
 *
 *
 * @version 1.0
 *
 */
@RestController
@RequestMapping("/activity")
@Slf4j
public class ActivityController extends BaseController {

    private final ActivityService activityService;

    private final CommonService commonService;

    private final UsersClient usersClient;
    @Resource
    private RedisService redisService;
    @Autowired
    private SysConfigUtil sysConfigUtil;

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private CouponRecordsDao couponRecordsDao;

    @Resource
    private ProductDao productDao;


    public ActivityController(ActivityService activityService, CommonService commonService, UsersClient usersClient) {
        this.activityService = activityService;
        this.commonService = commonService;
        this.usersClient = usersClient;
    }


    @Autowired
    private FakeUserUtil fakeUserUtil;


    /**
     * 获取新秒杀活动列表(App、h5)
     */
    @GetMapping("/getNewSecKillColumn")
    public CommonResult getNewSecKillColumn() {
        NewKillResponse newKillResponse = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_KILL_V2.name() + TokenUtil.getDataType() + TokenUtil.getPlatformData();
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            newKillResponse = JSONObject.parseObject(s, NewKillResponse.class);
        } else {
            newKillResponse = activityService.getNewKillList();
            redisService.set(key, JSONObject.toJSONString(newKillResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(newKillResponse);
    }

    /**
     * 获取9.9秒杀的今日热抢和明日预告
     */
    @GetMapping("/getNineSecKillColumn")
    public CommonResult getNineSecKillColumn() {
        NewKillResponse newKillResponse = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_KILL_V2.name() + TokenUtil.getDataType() + "_NinePointNine_" + TokenUtil.getPlatformData();
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            newKillResponse = JSONObject.parseObject(s, NewKillResponse.class);
        } else {
            newKillResponse = activityService.getNineSecKillColumn();
            redisService.set(key, JSONObject.toJSONString(newKillResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(newKillResponse);
    }

    /**
     * 秒杀排行
     *
     * @return)
     */
    @GetMapping("/getSeckillRank")
    public CommonResult getSeckillRank(@RequestParam("columnId") Integer columnId) {
        SeckillRankResponse seckillRankResponse = new SeckillRankResponse();
        seckillRankResponse.setProductActivityResponseList(activityService.getSeckillRank(columnId));
        seckillRankResponse.setVolumeStr("8W+");
        return CommonResult.success(seckillRankResponse);
    }

    /**
     * 新人首单商品列表
     *
     * @return
     */
    @GetMapping("/getNewUserProductList")
    public CommonResult getNewUserProductList() {
        ActivityResponse activityResponse = new ActivityResponse();
        String s = redisService.get(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_USER.name() + TokenUtil.getDataType());
        if (StringUtils.isNotEmpty(s)) {
            activityResponse = JSONObject.parseObject(s, ActivityResponse.class);
        } else {
            activityResponse.setBanners(commonService.getBannersInfoByType(ActivityTypeEnums.NEW_USER.name()));
            activityResponse.setProductActivityList(activityService.getNewUserProductList());
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_USER.name() + TokenUtil.getDataType(), JSONObject.toJSONString(activityResponse));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_USER.name() + TokenUtil.getDataType(), Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(activityResponse);
    }

    /**
     * 以旧换新活动栏目
     *
     * @return
     */
    @GetMapping("/getOldForNewColumn")
    public CommonResult getOldForNewColumn() {
        ActivityResponse activityResponse = new ActivityResponse();
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.OLD_FOR_NEW_V2.name() + TokenUtil.getDataType() + TokenUtil.getPlatformData();
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            activityResponse = JSONObject.parseObject(s, ActivityResponse.class);
        } else {
            activityResponse.setBanners(commonService.getBannersInfoByType(ActivityTypeEnums.OLD_FOR_NEW.name()));
            activityResponse.setActivityColumnList(activityService.getOldForNewColumn());
            redisService.set(key, JSONObject.toJSONString(activityResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(activityResponse);
    }

    /**
     * 补贴活动栏目
     *
     * @return
     */
    @GetMapping("/getSubsidyList")
    public CommonResult getSubsidyList() {
        ActivityResponse activityResponse = new ActivityResponse();
        String s = redisService.get(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.SUBSIDY.name() + TokenUtil.getDataType());
        if (StringUtils.isNotEmpty(s)) {
            activityResponse = JSONObject.parseObject(s, ActivityResponse.class);
        } else {
            activityResponse.setBanners(commonService.getBannersInfoByType(ActivityTypeEnums.SUBSIDY.name()));
            activityResponse.setActivityColumnMap(activityService.getSubsidyList());
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.SUBSIDY.name() + TokenUtil.getDataType(), JSONObject.toJSONString(activityResponse));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.SUBSIDY.name() + TokenUtil.getDataType(), Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(activityResponse);
    }

    /**
     * 获取新品招募商品列表
     *
     * @return
     */
    @GetMapping("/getNewProductList")
    public CommonResult getNewProductList() {
        ActivityResponse activityResponse = new ActivityResponse();
        String s = redisService.get(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_PRO.name() + TokenUtil.getDataType());
        if (StringUtils.isNotEmpty(s)) {
            activityResponse = JSONObject.parseObject(s, ActivityResponse.class);
        } else {
            activityResponse.setBanners(commonService.getBannersInfoByType(ActivityTypeEnums.NEW_PRO.name()));
            activityResponse.setProductActivityList(activityService.getNewProductList());
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_PRO.name() + TokenUtil.getDataType(), JSONObject.toJSONString(activityResponse));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.NEW_PRO.name() + TokenUtil.getDataType(), Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(activityResponse);
    }

    /**
     * 获取活动商品详情
     *
     * @param productId
     * @return
     */
    @GetMapping("/getActivityProductInfo")
    public CommonResult getActivityProductInfo(@RequestParam("productId") Integer productId,
                                               @RequestParam(value = "type", required = false) String type,
                                               @RequestParam(value = "pageSourceV2", required = false) String modular) {
        ProductResponse activityResponse = null;
        if ("h5".equals(TokenUtil.getRequest().getHeader("source"))) {
            activityResponse = activityService.getActivityProductInfo(productId, type, modular);
        } else {
            UsersResponse currentUser = getH5CurrentUser();
            if (currentUser == null) {
                activityResponse = activityService.getActivityProductInfo(productId, type, modular);
            } else {
                activityResponse = activityService.getActivityProductInfoV2(productId, type, currentUser, modular);
            }
        }
        activityResponse.setSpecMap(activityService.getActivityProductSpecList(productId).stream()
                .collect(Collectors.toMap(item -> {
                    String skuSpec = item.getSkuSpec();
                    String[] specList = skuSpec.split(",");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < specList.length; i++) {
                        String key = specList[i].split(":")[1];
                        if (i == specList.length - 1) {
                            stringBuilder.append(key);
                        } else {
                            stringBuilder.append(key).append("-");
                        }
                    }
                    return stringBuilder.toString();
                }, item -> item)));
        if (activityResponse.getIsAdvert() == 1) {
            String advertTips = TipsUtil.getTipsByActivityType(type);
            activityResponse.setAdvertTips(advertTips);
            return CommonResult.failed(ResultCode.NO_ADVERT, advertTips);
        }
        return CommonResult.success(activityResponse);
    }

    /**
     * 获取积分产品列表 app
     *
     * @return
     */
    @GetMapping("/getScoreProductList")
    public CommonResult getScoreProductList(@RequestParam(value = "brandId", required = false) Integer brandId) {
        UsersResponse user = this.getH5CurrentUser();
        ScorePageResponse appScoreProduct = activityService.getScoreProductList(user, brandId);
        return CommonResult.success(appScoreProduct);
    }


    /**
     * 获取h5积分产品列表 h5
     *
     * @return
     */
    @GetMapping("/getH5ScoreProductList")
    public CommonResult getH5ScoreProductList(@RequestParam(value = "brandId", required = false) Integer brandId) {
        UsersResponse user = this.getH5CurrentUser();
        H5ScorePageResponse h5ScorePageResponse = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_H5";
        if (brandId != null) {
            h5ScorePageResponse = activityService.getH5ScoreProductList(user, brandId);
        } else {
            String s = redisService.get(key);
            if (StringUtils.isNotEmpty(s)) {
                h5ScorePageResponse = JSONObject.parseObject(s, H5ScorePageResponse.class);
            } else {
                h5ScorePageResponse = activityService.getH5ScoreProductList(user, brandId);
                redisService.set(key, JSONObject.toJSONString(h5ScorePageResponse));
                redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
            }
        }
        // 最新未支付的订单
        List<Orders> ordersList = ordersDao.queryNewUsersOrderIdH5(TokenUtil.getToken());
        if (!CollectionUtils.isEmpty(ordersList)) {
            h5ScorePageResponse.setOrderId(ordersList.get(0).getId());
        }
        // 签到
        H5SignResponse h5SignResponse = new H5SignResponse();
        // 默认积分
        h5SignResponse.setExclusiveScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        // 是否签到
        String signStr = redisService.get(com.ytjj.common.constants.RedisConstants.H5_SIGN +
                Optional.ofNullable(TokenUtil.getToken()).orElse("xxx"));
        SignDto signDto = null;
        if (signStr != null) {
            signDto = JSONObject.parseObject(signStr, SignDto.class);
            try {
                int isYeaterday = DateUtils.isYeaterday(signDto.getSignTime(), new Date());
                if (isYeaterday == -1) {
                    h5SignResponse.setIsSign(1);
                } else if (isYeaterday == 1) {
                    h5SignResponse.setIsSign(0);
                } else {
                    h5SignResponse.setIsSign(0);
                    redisService.remove(com.ytjj.common.constants.RedisConstants.H5_SIGN + TokenUtil.getToken());
                    signDto = null;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            h5SignResponse.setIsSign(0);
        }
        h5SignResponse.setTomorrowScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.H5_SIGN_SCORE)));
        Map<String, Object> result = new HashMap<>();
        result.put("h5ScorePageResponse", h5ScorePageResponse);
        result.put("h5SignResponse", h5SignResponse);
        return CommonResult.success(result);
    }

    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5
     *
     * @return
     */
    @GetMapping("/getH5ScoreListByColumn")
    public CommonResult getH5ScoreListByColumn(@RequestParam(value = "type") String type) {
        UsersResponse user = this.getH5CurrentUser();
        H5ScorePageResponse h5ScorePageResponse = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_H5" + type;
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            h5ScorePageResponse = JSONObject.parseObject(s, H5ScorePageResponse.class);
        } else {
            h5ScorePageResponse = activityService.getH5ScoreListByColumn(type);
            redisService.set(key, JSONObject.toJSONString(h5ScorePageResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        // 最新未支付的订单
        List<Orders> ordersList = ordersDao.queryNewUsersOrderIdH5(TokenUtil.getToken());
        if (!CollectionUtils.isEmpty(ordersList)) {
            h5ScorePageResponse.setOrderId(ordersList.get(0).getId());
        }
        // 签到
        H5SignResponse h5SignResponse = new H5SignResponse();
        // 默认积分
        h5SignResponse.setExclusiveScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        // 是否签到
        String signStr = redisService.get(com.ytjj.common.constants.RedisConstants.H5_SIGN +
                Optional.ofNullable(TokenUtil.getToken()).orElse("xxx"));
        SignDto signDto = null;
        if (signStr != null) {
            signDto = JSONObject.parseObject(signStr, SignDto.class);
            try {
                int isYeaterday = DateUtils.isYeaterday(signDto.getSignTime(), new Date());
                if (isYeaterday == -1) {
                    h5SignResponse.setIsSign(1);
                } else if (isYeaterday == 1) {
                    h5SignResponse.setIsSign(0);
                } else {
                    h5SignResponse.setIsSign(0);
                    redisService.remove(com.ytjj.common.constants.RedisConstants.H5_SIGN + TokenUtil.getToken());
                    signDto = null;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            h5SignResponse.setIsSign(0);
        }
        h5SignResponse.setTomorrowScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.H5_SIGN_SCORE)));
        Map<String, Object> result = new HashMap<>();
        result.put("h5ScorePageResponse", h5ScorePageResponse);
        result.put("h5SignResponse", h5SignResponse);
        return CommonResult.success(result);
    }

    /**
     * 根据不同积分活动栏目获取app积分产品列表 app
     *
     * @return
     */
    @GetMapping("/getScoreListByColumn")
    public CommonResult getScoreListByColumn(@RequestParam(value = "type") String type) {
        UsersResponse user = this.getH5CurrentUser();
        ScorePageResponse appScoreProduct = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_APP" + type;
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            appScoreProduct = JSONObject.parseObject(s, ScorePageResponse.class);
        } else {
            appScoreProduct = activityService.getScoreListByColumn(user, type);
            redisService.set(key, JSONObject.toJSONString(appScoreProduct));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }

        return CommonResult.success(appScoreProduct);
    }

    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @GetMapping("/getH5ScoreListByType")
    public CommonResult getH5ScoreListByType(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
//        UsersResponse user = this.getH5CurrentUser();
        H5ScorePageResponse h5ScorePageResponse;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_H5_" + flag+"_"+TokenUtil.getSourcePlatform();
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            h5ScorePageResponse = JSONObject.parseObject(s, H5ScorePageResponse.class);
        } else {
            h5ScorePageResponse = activityService.getH5ScoreListByType(flag);
            redisService.set(key, JSONObject.toJSONString(h5ScorePageResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }

        String newUserOrderIsNotPayKey = RedisConstants.NEW_NOT_PAY_ORDERS + TokenUtil.getToken();
        Set<Object> newUserOrderIsNotPayByRedis = redisService.sGet(newUserOrderIsNotPayKey);
        if (newUserOrderIsNotPayByRedis.isEmpty()) {
            // 最新未支付的订单
            List<Orders> ordersList = ordersDao.queryNewUsersOrderIdH5Limit(TokenUtil.getToken());
            if (!CollectionUtils.isEmpty(ordersList)) {
                h5ScorePageResponse.setOrderId(ordersList.get(0).getId());
            }
            ordersList.stream().forEach(item -> {
                redisService.sSetAndTime(newUserOrderIsNotPayKey, 60, com.gexin.fastjson.JSON.toJSONString(item));
            });
        } else {
            Iterator iterator = newUserOrderIsNotPayByRedis.iterator();
            List<Orders> activityColumnList = new LinkedList<>();
            while (iterator.hasNext()) {
                String activityColumnStr = (String) iterator.next();
                Orders productImg = com.alibaba.fastjson.JSONObject.parseObject(activityColumnStr, Orders.class);
                activityColumnList.add(productImg);
            }
            h5ScorePageResponse.setOrderId(activityColumnList.get(0).getId());
        }

        // 签到
        H5SignResponse h5SignResponse = new H5SignResponse();
        // 默认积分
        h5SignResponse.setExclusiveScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        // 是否签到
        String signStr = redisService.get(com.ytjj.common.constants.RedisConstants.H5_SIGN +
                Optional.ofNullable(TokenUtil.getToken()).orElse("xxx"));
        if (signStr != null) {
            SignDto signDto = JSONObject.parseObject(signStr, SignDto.class);
            try {
                int isYeaterday = DateUtils.isYeaterday(signDto.getSignTime(), new Date());
                if (isYeaterday == -1) {
                    h5SignResponse.setIsSign(1);
                } else if (isYeaterday == 1) {
                    h5SignResponse.setIsSign(0);
                } else {
                    h5SignResponse.setIsSign(0);
                    redisService.remove(com.ytjj.common.constants.RedisConstants.H5_SIGN + TokenUtil.getToken());
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            h5SignResponse.setIsSign(0);
        }
        h5SignResponse.setTomorrowScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.H5_SIGN_SCORE)));
        // 今天是否购买免费兑商品
//        Integer count = ordersDao.queryIsBuyFree(TokenUtil.getToken());
        Map<String, Object> result = new HashMap<>();
        result.put("h5ScorePageResponse", h5ScorePageResponse);
        result.put("h5SignResponse", h5SignResponse);
        result.put("isBuy", 1);
        return CommonResult.success(result);
    }

    /**
     * 偏远地区活动
     * 根据不同积分活动栏目获取h5积分产品列表 h5, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @GetMapping("/getH5ScoreListByTypeForRemote")
    public CommonResult getH5ScoreListByTypeForRemote(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
//        UsersResponse user = this.getH5CurrentUser();
        H5ScorePageResponse h5ScorePageResponse;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_H5_" + flag+"_"+TokenUtil.getSourcePlatform() + "_REMOTE";
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            h5ScorePageResponse = JSONObject.parseObject(s, H5ScorePageResponse.class);
        } else {
            h5ScorePageResponse = activityService.getH5ScoreListByTypeForRemote(flag);
            redisService.set(key, JSONObject.toJSONString(h5ScorePageResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }

        String newUserOrderIsNotPayKey = RedisConstants.NEW_NOT_PAY_ORDERS + TokenUtil.getToken();
        Set<Object> newUserOrderIsNotPayByRedis = redisService.sGet(newUserOrderIsNotPayKey);
        if (newUserOrderIsNotPayByRedis.isEmpty()) {
            // 最新未支付的订单
            List<Orders> ordersList = ordersDao.queryNewUsersOrderIdH5Limit(TokenUtil.getToken());
            if (!CollectionUtils.isEmpty(ordersList)) {
                h5ScorePageResponse.setOrderId(ordersList.get(0).getId());
            }
            ordersList.stream().forEach(item -> {
                redisService.sSetAndTime(newUserOrderIsNotPayKey, 60, com.gexin.fastjson.JSON.toJSONString(item));
            });
        } else {
            Iterator iterator = newUserOrderIsNotPayByRedis.iterator();
            List<Orders> activityColumnList = new LinkedList<>();
            while (iterator.hasNext()) {
                String activityColumnStr = (String) iterator.next();
                Orders productImg = com.alibaba.fastjson.JSONObject.parseObject(activityColumnStr, Orders.class);
                activityColumnList.add(productImg);
            }
            h5ScorePageResponse.setOrderId(activityColumnList.get(0).getId());
        }

        // 签到
        H5SignResponse h5SignResponse = new H5SignResponse();
        // 默认积分
        h5SignResponse.setExclusiveScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        // 是否签到
        String signStr = redisService.get(com.ytjj.common.constants.RedisConstants.H5_SIGN +
                Optional.ofNullable(TokenUtil.getToken()).orElse("xxx"));
        if (signStr != null) {
            SignDto signDto = JSONObject.parseObject(signStr, SignDto.class);
            try {
                int isYeaterday = DateUtils.isYeaterday(signDto.getSignTime(), new Date());
                if (isYeaterday == -1) {
                    h5SignResponse.setIsSign(1);
                } else if (isYeaterday == 1) {
                    h5SignResponse.setIsSign(0);
                } else {
                    h5SignResponse.setIsSign(0);
                    redisService.remove(com.ytjj.common.constants.RedisConstants.H5_SIGN + TokenUtil.getToken());
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            h5SignResponse.setIsSign(0);
        }
        h5SignResponse.setTomorrowScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.H5_SIGN_SCORE)));
        // 今天是否购买免费兑商品
        Integer count = ordersDao.queryIsBuyFree(TokenUtil.getToken());
        Map<String, Object> result = new HashMap<>();
        result.put("h5ScorePageResponse", h5ScorePageResponse);
        result.put("h5SignResponse", h5SignResponse);
        result.put("isBuy",count);
        return CommonResult.success(result);
    }

    /**
     * h5 根据品牌id 查询商品列表
     *
     * @return
     */
    @GetMapping("/getProductsByBrandId")
    public CommonResult getProductsByBrandId(@RequestParam(value = "brandId") Integer brandId) {
        BrandScoreResponse response = activityService.getProductsByBrandId(brandId);
        return CommonResult.success(response);
    }

    /**
     * h5 用户签到领取红包
     *
     * @return
     */
    @GetMapping("/signCoupon")
    public CommonResult signCoupon() {
        UsersResponse h5CurrentUser = this.getH5CurrentUser();
        return CommonResult.success(activityService.signCoupon(h5CurrentUser));
    }

    /**
     * app 用户签到领取红包
     *
     * @return
     */
    @GetMapping("/signCouponApp")
    public CommonResult signCouponApp() {
        UsersResponse h5CurrentUser = this.getH5CurrentUser();
        return CommonResult.success(activityService.signCouponApp(h5CurrentUser));
    }

    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @GetMapping("/getH5ScoreListByTypeV2")
    public CommonResult getH5ScoreListByTypeV2(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
//        UsersResponse user = this.getH5CurrentUser();
        H5ScorePageResponse h5ScorePageResponse = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_H5_V2_" + flag;
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            h5ScorePageResponse = JSONObject.parseObject(s, H5ScorePageResponse.class);
        } else {
            h5ScorePageResponse = activityService.getH5ScoreListByTypeV2(flag);
            redisService.set(key, JSONObject.toJSONString(h5ScorePageResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        // 最新未支付的订单
        List<Orders> ordersList = ordersDao.queryNewUsersOrderIdH5(TokenUtil.getToken());
        if (!CollectionUtils.isEmpty(ordersList)) {
            h5ScorePageResponse.setOrderId(ordersList.get(0).getId());
        }
        // 签到
        H5SignResponse h5SignResponse = new H5SignResponse();
        // 默认积分
        h5SignResponse.setExclusiveScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        // 是否签到
        String signStr = redisService.get(com.ytjj.common.constants.RedisConstants.H5_SIGN +
                Optional.ofNullable(TokenUtil.getToken()).orElse("xxx"));
        if (signStr != null) {
            SignDto signDto = JSONObject.parseObject(signStr, SignDto.class);
            try {
                int isYeaterday = DateUtils.isYeaterday(signDto.getSignTime(), new Date());
                if (isYeaterday == -1) {
                    h5SignResponse.setIsSign(1);
                } else if (isYeaterday == 1) {
                    h5SignResponse.setIsSign(0);
                } else {
                    h5SignResponse.setIsSign(0);
                    redisService.remove(com.ytjj.common.constants.RedisConstants.H5_SIGN + TokenUtil.getToken());
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            h5SignResponse.setIsSign(0);
        }
        h5SignResponse.setTomorrowScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.H5_SIGN_SCORE)));
        Map<String, Object> result = new HashMap<>();
        result.put("h5ScorePageResponse", h5ScorePageResponse);
        result.put("h5SignResponse", h5SignResponse);
        return CommonResult.success(result);
    }

    /**
     * 根据不同积分活动栏目获取app积分产品列表 app, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @GetMapping("/getScoreListByType")
    public CommonResult getScoreListByType() {
        UsersResponse user = this.getH5CurrentUser();
        ScorePageResponse appScoreProduct = activityService.getScoreListByType(user);
        return CommonResult.success(appScoreProduct);
    }

    /**
     * app获取后台卡券兑换活动栏目
     * @return
     */
    @GetMapping("/appGetScoreListByType")
    public CommonResult getScoreListByTypeCopy() {
        UsersResponse user = getCurrentUser();
        ScorePageResponse appScoreProduct = activityService.getScoreListByTypeCopy(user);
        return CommonResult.success(appScoreProduct);
    }

    /**
     * 在积分页面 app, 返回品牌列表和用户头像和用户人数
     *
     * @return
     */
    @GetMapping("/getBrandsAndUsersHeadImg")
    public CommonResult getBrandsAndUsersHeadImg() {
        return CommonResult.success(activityService.getBrandsAndUsersHeadImg());
    }

    /**
     * 根据不同积分活动栏目获取app积分产品列表 app, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @GetMapping("/getScoreListByTypeV2")
    public CommonResult getScoreListByTypeV2(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
        UsersResponse user = this.getH5CurrentUser();
        ScorePageResponse appScoreProduct = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_APP_V2_" + flag;
//        String s = redisService.get(key);
//        if (StringUtils.isNotEmpty(s)) {
//            appScoreProduct = JSONObject.parseObject(s, ScorePageResponse.class);
//        } else {
//        appScoreProduct = activityService.getScoreListByType(user);
        appScoreProduct = activityService.getScoreListByTypeV2(user, flag);
//            redisService.set(key, JSONObject.toJSONString(appScoreProduct));
//            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
//        }

        return CommonResult.success(appScoreProduct);
    }

    /**
     * 获取商品相关推荐
     *
     * @param activityType
     * @return
     */
    @GetMapping("/getActivityCorrelationPro")
    public CommonResult getActivityCorrelationPro(@RequestParam(value = "activityType") String activityType,
                                                  @RequestParam("productId") Integer productId) {
        return CommonResult.success(activityService.getActivityCorrelationPro(activityType, productId));
    }

    /**
     * 我的钱包首页
     *
     * @return
     */
    @GetMapping("/myWallet")
    public CommonResult myWallet() {
        UsersResponse user = null;
        if (MyWalletConstant.SOURCE_H5.equals(getSource()) || MyWalletConstant.SOURCE_QA.equals(getSource())) {
            user = this.getH5CurrentUser();
        } else {
            user = this.getCurrentUser();
        }
        WalletResponse walletResponse = new WalletResponse();
        walletResponse.setUser(usersClient.getUsersInfo(user.getId()));
        walletResponse.getUser().setTel(user.getTel());
        walletResponse.setIsSign(user.getIsSign());
        walletResponse.setReturnCash(activityService.getReturnCashProductList());
        return CommonResult.success(walletResponse);
    }

    /**
     * @Description 用户红包获取
     *
     *
     */
    @GetMapping("/getRedEnvelope")
    public CommonResult getRedEnvelope() {
        // redis获取用户
        UsersResponse h5CurrentUser = getH5CurrentUser();
        BigDecimal money = h5CurrentUser.getMoney();
        // redis获取红包(第一天)配置数额
        List<EnvelopeConfig> formerEnvelopeConfigList = Optional.ofNullable(redisService.range(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_CONFIG_FORMER, 0, -1))
                .map(item -> item.stream()
                        .map(childItem -> JSONObject.parseObject((String) childItem, EnvelopeConfig.class))
                        .sorted(Comparator.comparing(EnvelopeConfig::getId))
                        .collect(Collectors.toList()))
                .orElse(new ArrayList<>());

        // redis获取红包(非第一天)配置数额
        List<EnvelopeConfig> latterEnvelopeConfigList = Optional.ofNullable(redisService.range(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_CONFIG_LATTER, 0, -1))
                .map(item -> item.stream()
                        .map(childItem -> JSONObject.parseObject((String) childItem, EnvelopeConfig.class))
                        .sorted(Comparator.comparing(EnvelopeConfig::getId))
                        .collect(Collectors.toList()))
                .orElse(new ArrayList<>());
        // 读取redis中的红包记录
        String redEnvelopeStr = redisService.get(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken());
        RedEnvelopeDto redEnvelopeDto = new RedEnvelopeDto();

        // 首天第一次领取
        if (!h5CurrentUser.getFlag() && redEnvelopeStr == null) {
            redEnvelopeDto.setReceiveTime(System.currentTimeMillis())
                    .setNextReceiveTime(System.currentTimeMillis() + Long.valueOf(formerEnvelopeConfigList.get(0).getExtra()) * 1000)
                    .setEnvelopeId(formerEnvelopeConfigList.get(0).getId())
                    .setNextEnvelopeId(formerEnvelopeConfigList.get(1).getId())
                    .setRedEnvelopeMoney(formerEnvelopeConfigList.get(0).getEnvelopeMoney());

            // 领取红包后所剩余额
            BigDecimal resultMoney = new BigDecimal(String.valueOf(formerEnvelopeConfigList.get(0).getEnvelopeMoney())).add(money);
            h5CurrentUser.setFlag(true)
                    .setMoney(resultMoney)
                    .setTotalMoney(resultMoney);
            // 更新redis用户信息
            redisService.set(h5CurrentUser.getToken(), JSONObject.toJSONString(h5CurrentUser));
            redisService.expire(h5CurrentUser.getToken(), TokenConstants.EXPIRE_SECONDS);
            // 更新redis红包领取记录
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), JSONObject.toJSONString(redEnvelopeDto));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), getSecondsNextEarlyMorning());
            return CommonResult.success(redEnvelopeDto);
        }
        // 首次其他次领取
        if (h5CurrentUser.getFlag() && redEnvelopeStr != null && !h5CurrentUser.getEndFlag()) {
            RedEnvelopeDto redEnvelope = JSONObject.parseObject(redEnvelopeStr, RedEnvelopeDto.class);
            if (System.currentTimeMillis() < redEnvelope.getNextReceiveTime()) {
                return CommonResult.failed("领取红包时间还未到，请您耐心等候!");
            }
            Integer currentEnvelopeId = redEnvelope.getNextEnvelopeId();
            if (currentEnvelopeId > formerEnvelopeConfigList.size()) {
                return CommonResult.failed("今天红包领取已达上限！");
            }
            redEnvelopeDto.setReceiveTime(System.currentTimeMillis())
                    .setNextReceiveTime(System.currentTimeMillis() + Long.valueOf(formerEnvelopeConfigList.get(currentEnvelopeId - 1).getExtra()) * 1000)
                    .setEnvelopeId(currentEnvelopeId)
                    .setNextEnvelopeId(currentEnvelopeId + 1)
                    .setRedEnvelopeMoney(formerEnvelopeConfigList.get(currentEnvelopeId - 1).getEnvelopeMoney());
            // 领取红包后所剩余额
            BigDecimal resultMoney = new BigDecimal(String.valueOf(formerEnvelopeConfigList.get(currentEnvelopeId - 1).getEnvelopeMoney())).add(money);
            h5CurrentUser.setMoney(resultMoney)
                    .setTotalMoney(resultMoney);
            // 更新redis用户信息
            redisService.set(h5CurrentUser.getToken(), JSONObject.toJSONString(h5CurrentUser));
            redisService.expire(h5CurrentUser.getToken(), TokenConstants.EXPIRE_SECONDS);
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), JSONObject.toJSONString(redEnvelopeDto));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), getSecondsNextEarlyMorning());
            return CommonResult.success(redEnvelopeDto);
        }
        /**********第二天之后的操作***********/
        // 非首天 第一次操作
        if (h5CurrentUser.getFlag() && redEnvelopeStr == null) {
            redEnvelopeDto.setReceiveTime(System.currentTimeMillis())
                    .setNextReceiveTime(System.currentTimeMillis() + Long.valueOf(latterEnvelopeConfigList.get(0).getExtra()) * 1000)
                    .setEnvelopeId(latterEnvelopeConfigList.get(0).getId())
                    .setNextEnvelopeId(latterEnvelopeConfigList.get(1).getId())
                    .setRedEnvelopeMoney(latterEnvelopeConfigList.get(0).getEnvelopeMoney());
            // 领取红包后所剩余额
            BigDecimal resultMoney = new BigDecimal(String.valueOf(latterEnvelopeConfigList.get(0).getEnvelopeMoney())).add(money);
            h5CurrentUser.setEndFlag(true)
                    .setMoney(resultMoney)
                    .setTotalMoney(resultMoney);
            // 更新redis用户信息
            redisService.set(h5CurrentUser.getToken(), JSONObject.toJSONString(h5CurrentUser));
            redisService.expire(h5CurrentUser.getToken(), TokenConstants.EXPIRE_SECONDS);
            // 更新redis红包领取记录
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), JSONObject.toJSONString(redEnvelopeDto));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), getSecondsNextEarlyMorning());
            return CommonResult.success(redEnvelopeDto);
        }
        // 非首次其他次领取
        if (h5CurrentUser.getFlag() && redEnvelopeStr != null && h5CurrentUser.getEndFlag()) {
            RedEnvelopeDto redEnvelope = JSONObject.parseObject(redEnvelopeStr, RedEnvelopeDto.class);
            Integer currentEnvelopeId = redEnvelope.getNextEnvelopeId();
            Integer size = latterEnvelopeConfigList.size();
            if (currentEnvelopeId > latterEnvelopeConfigList.size() * 2) {
                return CommonResult.failed("今天红包领取已达上限！");
            }
            if (System.currentTimeMillis() < redEnvelope.getNextReceiveTime()) {
                return CommonResult.failed("领取时间还未到，请耐心等候!");
            }
            redEnvelopeDto.setReceiveTime(System.currentTimeMillis())
                    .setNextReceiveTime(System.currentTimeMillis() + Long.valueOf(latterEnvelopeConfigList.get(currentEnvelopeId - size - 1).getExtra()) * 1000)
                    .setEnvelopeId(currentEnvelopeId)
                    .setNextEnvelopeId(currentEnvelopeId + 1)
                    .setRedEnvelopeMoney(latterEnvelopeConfigList.get(currentEnvelopeId - size - 1).getEnvelopeMoney());
            // 领取红包后所剩余额
            BigDecimal resultMoney = new BigDecimal(String.valueOf(latterEnvelopeConfigList.get(currentEnvelopeId - size - 1).getEnvelopeMoney())).add(money);
            h5CurrentUser.setMoney(resultMoney)
                    .setTotalMoney(resultMoney);
            // 更新redis用户信息
            redisService.set(h5CurrentUser.getToken(), JSONObject.toJSONString(h5CurrentUser));
            redisService.expire(h5CurrentUser.getToken(), TokenConstants.EXPIRE_SECONDS);
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), JSONObject.toJSONString(redEnvelopeDto));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.RED_ENVELOPE_RECORD + h5CurrentUser.getToken(), getSecondsNextEarlyMorning());
            return CommonResult.success(redEnvelopeDto);
        }
        return CommonResult.failed(ResultCode.FAILED);
    }


    /**
     * 我的钱包签到
     *
     * @return
     */
    @GetMapping("/myWalletSignIn")
    public CommonResult myWalletSignIn() {
        UsersResponse h5CurrentUser = getH5CurrentUser();
        // redis获取签到金额
        String signMoney = sysConfigUtil.getSysConfig(SysConfigConstants.WALLET_SIGN_MONEY);
        String str = redisService.get(RedisConstants.WALLET_PREFIX + h5CurrentUser.getToken());
        if (null != str) {
            return CommonResult.failed("不能重复发起签到");
        }
        BigDecimal newMoney = h5CurrentUser.getMoney().add(new BigDecimal(signMoney));
        // 设置签到情况
        WalletSignDto walletSignDto = new WalletSignDto()
                .setSignMoney(new BigDecimal(signMoney))
                .setSignDate(new Date())
                .setIsSign(true)
                .setTotalMoney(newMoney);
        redisService.set(RedisConstants.WALLET_PREFIX + h5CurrentUser.getToken(), JSONObject.toJSONString(walletSignDto));
        redisService.expire(RedisConstants.WALLET_PREFIX + h5CurrentUser.getToken(), getSecondsNextEarlyMorning());
        // 签到后缓存用户金额更改
        h5CurrentUser.setMoney(newMoney);
        h5CurrentUser.setTotalMoney(newMoney);
        h5CurrentUser.setIsSign(walletSignDto.getIsSign());
        // 更新redis
        redisService.set(h5CurrentUser.getToken(), JSONObject.toJSONString(h5CurrentUser));
        redisService.expire(h5CurrentUser.getToken(), TokenConstants.EXPIRE_SECONDS);
        return CommonResult.success(walletSignDto);
    }

    /**
     * 现金券 (h5)
     * (作废接口:2020-12-9)
     *
     * @return
     */
    @GetMapping("/getCashCoupon")
    public CommonResult getCashCoupon() {
        ActivityResponse activityResponse = new ActivityResponse();
        String s = redisService.get(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_COUPON.name() + TokenUtil.getDataType());
        if (StringUtils.isNotEmpty(s)) {
            activityResponse = JSONObject.parseObject(s, ActivityResponse.class);
        } else {
            activityResponse.setBanners(commonService.getBannersInfoByType(ActivityTypeEnums.CASH_COUPON.name()));
            activityResponse.setActivityColumnList(activityService.getCashCouponList());
            List<ProductResponse> allCashCouponList = activityService.getAllCashCouponList();
            Collections.shuffle(allCashCouponList);
            activityResponse.setProductActivityList(allCashCouponList);
            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_COUPON.name() + TokenUtil.getDataType(), JSONObject.toJSONString(activityResponse));
            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_COUPON.name() + TokenUtil.getDataType(), Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(activityResponse);
    }

    /**
     * 获取当前时间到第二天凌晨0：00的秒数
     *
     * @return
     */
    public static Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        // 改成这样就好了
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    /**
     * 拍卖
     *
     * @return
     */
//    @GetMapping("/getAuctionProductList")
//    public CommonResult getAuctionProductList() {
//        ActivityResponse activityResponse = new ActivityResponse();
//        String s = redisService.get(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.AUCTION.name() + TokenUtil.getDataType());
//        if (StringUtils.isNotEmpty(s)) {
//            activityResponse = JSONObject.parseObject(s, ActivityResponse.class);
//        } else {
//            activityResponse.setBanners(commonService.getBannersInfoByType(ActivityTypeEnums.AUCTION.name()));
//            activityResponse.setAuctionList(activityService.getAuctionProductList());
//            redisService.set(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.AUCTION.name() + TokenUtil.getDataType(), JSONObject.toJSONString(activityResponse));
//            redisService.expire(com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.AUCTION.name() + TokenUtil.getDataType(), Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
//        }
//        return CommonResult.success(activityResponse);
//    }


    /**
     * @Description 获取活动导航列表
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/getActivityNavList")
    public CommonResult getActivityNavList(@RequestParam("type") String type) {
        return CommonResult.success(activityService.getActivityNavList(type));
    }

    /**
     * @Description 获取活动banner列表
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/getActivityBannerList")
    public CommonResult getBannerList() {
        return CommonResult.success(activityService.getActivityBannerList());
    }


    /**
     * @Description 获取优惠商品列表 (老版本)（app）
     * @Version 1.0
     **/
    @GetMapping("/getCouponProductList")
    public CommonResult getCouponProductList() {
        UsersResponse currentUser = getCurrentUser();
        return CommonResult.success(activityService.getCouponProductList(currentUser.getId()));
    }

    /**
     * @Description 获取优惠商品列表 (新版本)(App)
     * @Version 1.0
     **/
    @GetMapping("/getCouponProductNewList")
    public CommonResult getCouponProductNewList() {
        UsersResponse currentUser = getCurrentUser();
        return CommonResult.success(activityService.getCouponProductNewList(currentUser.getId()));
    }

    /**
     * @Description 获取优惠商品列表 (h5/app通用)
     * @Version 1.0
     **/
    @GetMapping("/getAllCouponList")
    public CommonResult getAllCouponList() {
        return CommonResult.success(activityService.getAllCouponList());
    }

    /**
     * @Description 根据优惠券类型 获取优惠商品列表 (h5/app通用)
     * @Version 1.0
     **/
    @GetMapping("/getCouponProductListById")
    public CommonResult getCouponProductListById(@RequestParam(value = "id") Integer id,
                                                 @RequestParam(value = "pageNum") Integer pageNum,
                                                 @RequestParam(value = "pageSize") Integer pageSize) {
        return CommonResult.success(activityService.getCouponProductListById(id, pageNum, pageSize));
    }

    @Autowired
    private ProductService productService;

    /**
     * @return
     */
    @GetMapping("/getCouponListV1")
    public CommonResult getCouponListV1(@RequestParam("productId") Integer productId) {
        CouponListV1Response result = new CouponListV1Response();
//        String productIdstr = sysConfigUtil.getSysConfig("COUPON_PRODUCT_V1");
//        Integer productId = Integer.parseInt(productIdstr);
        ProductResponse productResponse = productService.getProductById(productId, "");
        List<ProductResponse> couponListV1 = activityService.getCouponListV1();
        // 是否领取
        Date nowDate = new Date();
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        couponListV1.stream()
                .map(item -> {
                    CouponRecords couponRecords = couponRecordsDao.queryOne(item.getId(), token, nowDate, source);
                    if (couponRecords != null) {
                        item.setIsReceive(2);
                        item.setOverdueTime(couponRecords.getOverdueTime());
                    }
                    return item;
                })
                .collect(Collectors.toList());
        CouponRecords couponRecords = couponRecordsDao.queryOne(productResponse.getId(), token, nowDate, source);
        if (couponRecords != null) {
            productResponse.setIsReceive(2);
            productResponse.setOverdueTime(couponRecords.getOverdueTime());
        }


        UsersResponse currentUser = getH5CurrentUser();
        // 是否收藏
        if (currentUser == null) {
            productResponse.setIsCollect(IsCollectConstant.NO);
        } else {
            if (!DynamicConstant.SOURCE_H5.equals(getSource())
                    && !DynamicConstant.SOURCE_QA.equals(getSource())) {
                productResponse.setIsCollect(
                        Optional.ofNullable(usersClient.isCollect(productResponse.getId(), currentUser.getId())).orElse(0));
            }
        }
        productResponse.setSpecMap(productService.getProductSpecList(productId).stream()
                .collect(Collectors.toMap(item -> {
                    String skuSpec = item.getSkuSpec();
                    String[] specList = skuSpec.split(",");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < specList.length; i++) {
                        String key = specList[i].split(":")[1];
                        if (i == specList.length - 1) {
                            stringBuilder.append(key);
                        } else {
                            stringBuilder.append(key).append("-");
                        }
                    }
                    return stringBuilder.toString();
                }, item -> item)));
        result.setDetails(productResponse);
        result.setProductList(couponListV1);
        return CommonResult.success(result);
    }


    /**
     * @Description 查询优惠券列表(优惠券跟每个商品走)
     * @Version 1.0
     **/
    @GetMapping("/getCouponList")
    public CommonResult getCouponList() {
        List<ProductResponse> couponList;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_COUPON.name() + TokenUtil.getPlatformData();
        String result = redisService.get(key);
        if (StringUtils.isNotEmpty(result)) {
            try {
                couponList = JSONArray.parseArray(result, ProductResponse.class);
            } catch (Exception e) {
                log.info("优惠券序列化异常：", e);
                couponList = activityService.getCouponList();
                redisService.set(key, JSON.toJSONString(couponList));
                redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
            }
        } else {
            couponList = activityService.getCouponList();
            redisService.set(key, JSON.toJSONString(couponList));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        // 是否领取
        Date nowDate = new Date();
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        couponList = couponList.stream()
                .map(item -> {
                    CouponRecords couponRecords = couponRecordsDao.queryOne(item.getId(), token, nowDate, source);
                    if (couponRecords != null) {
                        item.setIsReceive(2);
                        item.setOverdueTime(couponRecords.getOverdueTime());
                    }
                    return item;
                })
                .collect(Collectors.toList());

        return CommonResult.success(couponList);
    }

    /**
     * @Description 查询该用户优惠券使用情况 type:0未使用，1已使用，2失效
     * @Version 1.0
     **/
    @GetMapping("/getUserCouponList")
    public CommonResult getUserCouponList(@RequestParam Integer type) {
        UserCouponResponse result = activityService.getUserCouponList(type);
        return CommonResult.success(result);
    }

    /**
     * @Description 查询该用户优惠券使用情况 type:0未使用，1已使用，2失效
     * @Version 1.0
     **/
    @GetMapping("/getUserCouponListV2")
    public CommonResult getUserCouponListV2(@RequestParam Integer type) {
        UserCouponResponse result = activityService.getUserCouponListV2(type);
        return CommonResult.success(result);
    }

    /**
     * 领取优惠券
     *
     * @param productId
     * @return
     */
    @GetMapping("/obtainCoupon")
    public CommonResult obtainCoupon(@RequestParam Integer productId) {
        CouponRecords couponRecord = activityService.obtainCoupon(productId);
        return CommonResult.success(couponRecord);
    }

    /**
     * 优惠券列表v2
     *
     * @return
     */
    @GetMapping("/getCouponListV2")
    public CommonResult getCouponListV2() {
        UserCouponResponse userCouponResponse = activityService.getCouponListV2();
        return CommonResult.success(userCouponResponse);
    }

    /**
     * 优惠券列表v2,根据sort排序,获取前10个
     *
     * @return
     */
    @GetMapping("/getCouponListV2ByPage")
    public CommonResult getCouponListV2ByPage(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return CommonResult.success(activityService.getCouponListV2ByPage(pageNum, pageSize));
    }

    /**
     * 优惠券列表v3,根据sort排序
     *
     * @return
     */
    @GetMapping("/getCouponListV3ByPage")
    public CommonResult getCouponListV3ByPage(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                              @RequestParam(value = "couponPrice", required = false, defaultValue = "0") Integer couponPrice) {
        return CommonResult.success(activityService.getCouponListV3ByPage(pageNum, pageSize, couponPrice));
    }

    /**
     * 优惠券列表v4,新增签到等功能 h5
     *
     * @return
     */
    @GetMapping("/getCouponListV4ByPage")
    public CommonResult getCouponListV4ByPage(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        UserCouponResponseV2 data = activityService.getCouponListV4ByPage(pageNum, pageSize);
        // 签到
        String token =  TokenUtil.getToken();
        String key = com.ytjj.common.constants.RedisConstants.H5_SIGN + "coupon:" + token;
        String signStr = redisService.get(key);

        // 是否签到
        if (StringUtils.isNotEmpty(signStr)) {
            data.setIsSign(1);
        }
        return CommonResult.success(data);
    }

    /**
     * 优惠券列表v4,新增签到等功能 app
     *
     * @return
     */
    @GetMapping("/getCouponListAPP")
    public CommonResult getCouponListApp(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        UserCouponResponseV2 data = activityService.getCouponListV4ByPage(pageNum, pageSize);
        log.info("getToken : {}", TokenUtil.getToken());
        log.info("getUuid : {}", TokenUtil.getUuid());
        // 用户红包
//        data.setActivityMax(Optional.ofNullable(h5CurrentUser.getActivityMax()).orElse(new BigDecimal(680)));
        // 签到
//        UsersResponse h5CurrentUser = this.getH5CurrentUser();
        String token =  TokenUtil.getUuid();
        String key = com.ytjj.common.constants.RedisConstants.APP_SIGN + "coupon:" + token;
        String signStr = redisService.get(key);

        // 是否签到
        if (StringUtils.isNotEmpty(signStr)) {
            data.setIsSign(1);
        }
        return CommonResult.success(data);
    }

    /**
     * 领取优惠券 (老版本)
     *
     * @param couponId
     * @return
     */
    @GetMapping("/receiveCoupon")
    public CommonResult receiveCoupon(@RequestParam Integer couponId) {
        UsersResponse currentUser = getCurrentUser();
        UsersCouponDto usersCouponDto = activityService.receiveCoupon(currentUser.getId(), couponId);
        return CommonResult.success(usersCouponDto);
    }

    /**
     * 领取优惠券 (新版本)
     *
     * @param couponId
     * @return
     */
    @GetMapping("/receiveCouponNew")
    public CommonResult receiveCouponNew(@RequestParam Integer couponId) {
        UsersResponse currentUser = getCurrentUser();
        activityService.receiveCouponNew(currentUser.getId(), couponId);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 购买通知
     *
     * @return
     */
    @GetMapping("/buyNotice")
    public CommonResult buyNotice() {
        return CommonResult.success(activityService.buyNotice());
    }

    /**
     * 根据价格获取相应商品列表
     *
     * @return
     */
    @GetMapping("/getProductsByActivityMax")
    public CommonResult getProductsByActivityMax(@RequestParam(value = "activityMax") Integer activityMax) {
        List<ProductResponse> couponList = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_COUPON.name() + TokenUtil.getDataType() + activityMax;
        String result = redisService.get(key);
        if (StringUtils.isNotEmpty(result)) {
            try {
                couponList = JSONArray.parseArray(result, ProductResponse.class);
            } catch (Exception e) {
                log.info("优惠券序列化异常：", e);
                couponList = activityService.getProductsByActivityMax(new BigDecimal(activityMax));
                redisService.set(key, JSON.toJSONString(couponList));
                redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
            }
        } else {
            couponList = activityService.getProductsByActivityMax(new BigDecimal(activityMax));
            redisService.set(key, JSON.toJSONString(couponList));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return CommonResult.success(couponList);
    }

    /**
     * 用户中心积分商品
     *
     * @return
     */
    @GetMapping("/getUserCenterData")
    public CommonResult getUserCenterData() {
        UserCenterResponse result = activityService.getUserCenterData();
        return CommonResult.success(result);
    }

    /**
     * @Description : 兑换中心页
     */
    @GetMapping("/getChangeCenterData")
    public CommonResult getChangeCenterData() {
        UsersResponse usersResponse = this.getH5CurrentUser();
        ChangeCenterResponse changeCenterResponse = null;

        String key = "ChangeCenterData" + TokenUtil.getPlatformData();
        String result = redisService.get(key);
        if (StringUtils.isNotEmpty(result)) {
            changeCenterResponse = JSONObject.parseObject(result, ChangeCenterResponse.class);
        } else {
            changeCenterResponse = activityService.getChangeCenterData(usersResponse);
            redisService.set(key, JSON.toJSONString(changeCenterResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        // 默认积分
        changeCenterResponse.setExclusiveScore(usersResponse.getScore());
        return CommonResult.success(changeCenterResponse);
    }

    /**
     * @Description : 猜你喜欢
     */
    @GetMapping("/getLikeInRecharge")
    public CommonResult getLikeInRecharge() {
        return CommonResult.success(activityService.getLikeInRecharge());
    }


    /**
     * @Description : 保暖商品
     */
    @GetMapping("/getWarmProducts")
    public CommonResult getWarmProducts() {
        return CommonResult.success(activityService.getWarmProducts());
    }

    /**
     * @Description : 保暖商品, 根据商品id查询单品
     */
    @GetMapping("/getWarmProductsV2")
    public CommonResult getWarmProductsV2(@RequestParam("hotProductId") Integer hotProductId) {
        WarmProductResponse warmProductsV2 = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.EXTENSION + "_Warm_Products_V2_" + TokenUtil.getDataType() + hotProductId;
        String result = redisService.get(key);
        if (StringUtils.isNotEmpty(result)) {
            warmProductsV2 = JSONObject.parseObject(result, WarmProductResponse.class);
            return CommonResult.success(warmProductsV2);
        }
        warmProductsV2 = activityService.getWarmProductsV2(hotProductId);
        redisService.set(key, JSON.toJSONString(warmProductsV2));
        redisService.expire(key, ExpireTimeConstant.WARM_PRODUCTS_PAGE);
        return CommonResult.success(warmProductsV2);
    }

    /**
     * 以旧换新栏目 (h5)
     *
     * @param productId
     * @return
     */
    @GetMapping("/queryOldForNewData")
    public CommonResult queryOldForNewColumn(@RequestParam(value = "productId", required = false) Integer productId) {
        OldForNewExtResponse result = activityService.queryOldForNewColumn(productId);
        String token = TokenUtil.getToken();
        String recordKey = com.ytjj.qmyx.mall.constants.RedisConstants.RECORD_SUBSIDYKEY + token;
        String recordDto = redisService.get(recordKey);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(recordDto)) {
            result.setTotalReceive(BigDecimal.valueOf(0));
            result.setUsed(BigDecimal.valueOf(0));
            result.setNotUsed(BigDecimal.valueOf(0));
            result.setNotUsedNum(0);
            return CommonResult.success(result);
        }
        RecordSubsidyDataDto recordSubsidyDataDto = Optional.ofNullable(JSONObject.parseObject(recordDto, RecordSubsidyDataDto.class)).orElse(new RecordSubsidyDataDto());
        BigDecimal totalReceive = Optional.ofNullable(recordSubsidyDataDto.getReceived()).orElse(BigDecimal.ZERO);
        BigDecimal used = Optional.ofNullable(recordSubsidyDataDto.getUsed()).orElse(BigDecimal.ZERO);
        result.setTotalReceive(totalReceive.setScale(0, BigDecimal.ROUND_UP));
        result.setUsed(used.setScale(0, BigDecimal.ROUND_UP));
        result.setNotUsed(totalReceive.compareTo(used) > 0
                ? totalReceive.subtract(used).setScale(0, BigDecimal.ROUND_UP)
                : BigDecimal.ZERO);
        result.setNotUsedNum(redisService.getHashEntries(com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY + token).size());
        return CommonResult.success(result);
    }

    /**
     * 以旧换新栏目
     *
     * @param productId
     * @return
     */
    @GetMapping("/queryOldForNewDataApp")
    public CommonResult queryOldForNewDataApp(@RequestParam(value = "productId", required = false) Integer productId) {
        OldForNewExtResponse result = activityService.queryOldForNewColumnApp(productId);
        String token = TokenUtil.getUuid();
        String recordKey = com.ytjj.qmyx.mall.constants.RedisConstants.RECORD_SUBSIDYKEY_APP + token;
        String recordDto = redisService.get(recordKey);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(recordDto)) {
            result.setTotalReceive(BigDecimal.valueOf(0));
            result.setUsed(BigDecimal.valueOf(0));
            result.setNotUsed(BigDecimal.valueOf(0));
            result.setNotUsedNum(0);
            return CommonResult.success(result);
        }
        RecordSubsidyDataDto recordSubsidyDataDto = Optional.ofNullable(JSONObject.parseObject(recordDto, RecordSubsidyDataDto.class)).orElse(new RecordSubsidyDataDto());

        BigDecimal totalReceive = Optional.ofNullable(recordSubsidyDataDto.getReceived())
                .orElse(BigDecimal.ZERO);
        BigDecimal used = Optional.ofNullable(recordSubsidyDataDto.getUsed())
                .orElse(BigDecimal.ZERO);

        result.setTotalReceive(totalReceive.setScale(0, BigDecimal.ROUND_UP));
        result.setUsed(used.setScale(0, BigDecimal.ROUND_UP));
        result.setNotUsed(totalReceive.compareTo(used) > 0
                ? totalReceive.subtract(used).setScale(0, BigDecimal.ROUND_UP)
                : BigDecimal.ZERO);
        result.setNotUsedNum(redisService.getHashEntries(com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY_APP + token).size());
        return CommonResult.success(result);
    }

    /**
     * 以旧换新列表
     *
     * @return
     */
    @GetMapping("/queryOldForNewList")
    public CommonResult queryOldForNewList(@RequestParam(value = "columnId") Integer columnId) {

        String key = com.ytjj.qmyx.mall.constants.RedisConstants.EXTENSION + "oldForNew" + columnId;
        String s = redisService.get(key);
        List<OldForNewProductDto> productList = null;
        if (s != null) {
            productList = JSONArray.parseArray(s, OldForNewProductDto.class);
        } else {
            productList = activityService.queryOldForNewList(columnId);
            redisService.set(key, JSON.toJSONString(productList));
            redisService.expire(key, ExpireTimeConstant.OLDFORNEW_PAGE);
        }

        String subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
        String token = TokenUtil.getToken();
        productList = productList.stream()
                .map(i -> {
                    Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                    if (subsidyHash != null && subsidyHash.size() > 0) {
                        Object subsidyData = subsidyHash.get(i.getId().toString());
                        if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                            i.setIsReceiveSubsidy(1);
                        }
                    }
                    return i;
                })
                .collect(Collectors.toList());
//        if(columnId == 14){
//            productList = productList.stream()
//                    .sorted(Comparator.comparing(OldForNewProductDto::getIsReceiveSubsidy,
//                            (s1, s2) -> s2.compareTo(s1)))
//                    .collect(Collectors.toList());
//        }
        return CommonResult.success(productList);
    }

    /**
     * 以旧换新列表
     *
     * @return
     */
    @GetMapping("/queryOldForNewListApp")
    public CommonResult queryOldForNewListApp(@RequestParam(value = "columnId") Integer columnId) {

        String key = com.ytjj.qmyx.mall.constants.RedisConstants.EXTENSION_APP + "oldForNew" + columnId;
        String s = redisService.get(key);
        List<OldForNewProductDto> productList = null;
        if (s != null) {
            productList = JSONArray.parseArray(s, OldForNewProductDto.class);
        } else {
            productList = activityService.queryOldForNewList(columnId);
            redisService.set(key, JSON.toJSONString(productList));
            redisService.expire(key, ExpireTimeConstant.OLDFORNEW_PAGE);
        }

        String subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY_APP;
        String token = TokenUtil.getUuid();
        productList = productList.stream()
                .filter(item -> !isReceive(item.getId()))
                .map(i -> {
                    Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                    if (subsidyHash != null) {
                        Object subsidyData = subsidyHash.get(i.getId().toString());
                        if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                            i.setIsReceiveSubsidy(1);
                        }
                    }
                    return i;
                })
                .collect(Collectors.toList());
        if (columnId == 14) {
            productList = productList.stream()
                    .sorted(Comparator.comparing(OldForNewProductDto::getIsReceiveSubsidy,
                            (s1, s2) -> s2.compareTo(s1)))
                    .collect(Collectors.toList());
        }
        return CommonResult.success(productList);
    }

    /**
     * 该用户是否领取该商品
     *
     * @param productId
     * @return
     */
    private Boolean isReceive(Integer productId) {
        String subsidyKey;
        String token;
        if ("h5".equals(TokenUtil.getSource())) {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
            token = TokenUtil.getToken();
        } else {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY_APP;
            token = TokenUtil.getUuid();
        }
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
        if (subsidyHash != null && subsidyHash.size() > 0) {
            Object subsidyData = subsidyHash.get(productId.toString());
            if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                return true;
            }
        }
        return false;
    }

    @GetMapping("/getActivityList")
    private CommonResult getActivityList(@RequestParam(value = "pageNum", required = false) Integer pageNum,
                                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                         @RequestParam(required = false) String activityType,
                                         @RequestParam(required = false) BigDecimal activityMax,
                                         @RequestParam(required = false) String productName) {
        return CommonResult.success(activityService.getActivityList(pageNum, pageSize, activityType, activityMax, productName));
    }

    /**
     * 同上面接口区别在于限制了返回的商品售价
     * @param pageNum
     * @param pageSize
     * @param activityType
     * @param activityMax
     * @param productName
     * @return
     */
    @GetMapping("/getActivityListFixPrice")
    private CommonResult getActivityListFixPrice(@RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                 @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                 @RequestParam(required = false) String activityType,
                                                 @RequestParam(required = false) BigDecimal activityMax,
                                                 @RequestParam(required = false) String productName) {
        return CommonResult.success(activityService.getActivityListFixPrice(pageNum, pageSize, activityType, activityMax, productName));
    }

    /**
     * 根据活动类型,获取商品列表,根据sort排序
     *
     * @return
     */
    @GetMapping("/getProductsByType")
    public CommonResult getProductsByType(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                          @RequestParam(value = "activityType", required = false, defaultValue = "") String activityType) {
        return CommonResult.success(activityService.getProductsByBrandType(pageNum, pageSize, activityType));
    }

    /**
     * 获取补贴未领取的商品
     *
     * @return
     */
    @GetMapping("/getNotReceiveList")
    public CommonResult getNotReceiveList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        OldForNewReceiveResponse response = activityService.getNotReceiveList(pageNum,pageSize);
        return CommonResult.success(response);
    }

    /**
     * 获取补贴未领取的商品
     *
     * @return
     */
    @GetMapping("/getNotReceiveListV2")
    public CommonResult getNotReceiveListV2(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        OldForNewReceiveResponse response = activityService.getNotReceiveListV2(pageNum,pageSize);
        return CommonResult.success(response);
    }

    /**
     * 获取补贴未领取的商品
     *
     * @return
     */
    @GetMapping("/getNotReceiveListV3")
    public CommonResult getNotReceiveListV3(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        OldForNewReceiveResponse response = activityService.getNotReceiveListV3(pageNum,pageSize);
        return CommonResult.success(response);
    }

    /**
     * 获取用户已补贴商品 h5
     *
     * @return
     */
    @GetMapping("/getOldForNewProductsOfH5User")
    public CommonResult getOldForNewProductsOfH5User(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag,
                                                     @RequestParam(value = "columnId", required = false) Integer columnId,
                                                     @RequestParam(value = "activityMax", required = false) BigDecimal activityMax) {
        return CommonResult.success(activityService.getOldForNewProductsOfH5User(flag, columnId, activityMax));
    }

    /**
     * 获取用户已补贴商品 h5
     *
     * @return
     */
    @GetMapping("/getOldForNewOrders")
    public CommonResult getOldForNewOrders() {
        return CommonResult.success(activityService.getOldForNewOrders());
    }

    /**
     * 获取用户已补贴商品 app
     *
     * @return
     */
    @GetMapping("/getOldForNewProductsOfAppUser")
    public CommonResult getOldForNewProductsOfAppUser() {
        return CommonResult.success(activityService.getOldForNewProductsOfAppUser());
    }

    /**
     * 获取活动商品列表 h5
     * @return
     */
    @GetMapping("/getActivityListH5")
    public CommonResult getActivityListH5() {
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.NEWYEAR_GOODS;
        String s = redisService.get(key);
        ActivityH5Response activityH5Response;
        if (StringUtils.isEmpty(s)) {
            activityH5Response = activityService.getActivityListH5();
            redisService.set(key, JSON.toJSONString(activityH5Response));
            redisService.expire(key, ExpireTimeConstant.OLDFORNEW_PAGE);
        } else {
            activityH5Response = JSONObject.parseObject(s, ActivityH5Response.class);
        }
        activityH5Response.setOldForNewList(activityH5Response.getOldForNewList().stream().map(item ->{
            if(this.isReceive(item.getId())){
                item.setIsReceiveSubsidy(1);
            }else{
                item.setIsReceiveSubsidy(0);
            }
            return item;
        }).collect(Collectors.toList()));

        // 用户积分
        UsersResponse h5CurrentUser = this.getH5CurrentUser();
        if (h5CurrentUser == null) {
            activityH5Response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        } else {
            activityH5Response.setScore(h5CurrentUser.getScore());
        }
        // 用户红包
//        UsersResponse usersResponse = this.getUsersActivityMax();
        ReturnCouponResponse returnCouponResponse = this.getReturnCoupon();
        activityH5Response.setActivityMax(returnCouponResponse.getActivityMax());

        return CommonResult.success(activityH5Response);
    }

    private ReturnCouponResponse getReturnCoupon() {
        ReturnCouponResponse returnCouponResponse = new ReturnCouponResponse();
        String key;

        if ("h5".equals(TokenUtil.getSource())) {
            key = com.ytjj.qmyx.mall.constants.RedisConstants.RETURN_COUPON + TokenUtil.getToken();
        }else {
            key = com.ytjj.qmyx.mall.constants.RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid();
        }
        String cs = redisService.get(key);
        if (StringUtils.isNotEmpty(cs)) {// 记录用户返现红包金额
            returnCouponResponse = com.alibaba.fastjson.JSONObject.parseObject(cs, ReturnCouponResponse.class);
        }

        returnCouponResponse.setUsedActivityMax(Optional.ofNullable(returnCouponResponse.getUsedActivityMax())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setTotalReturnCoupon(Optional.ofNullable(returnCouponResponse.getTotalReturnCoupon())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setActivityMax(Optional.ofNullable(returnCouponResponse.getActivityMax())
                .orElse(new BigDecimal(680)).setScale(0, BigDecimal.ROUND_HALF_UP));

        return returnCouponResponse;
    }

    /**
     * 获取活动商品列表 app
     * @return
     */
    @GetMapping("/getActivityListApp")
    public CommonResult getActivityListApp() {
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.NEWYEAR_GOODS_APP;
        String s = redisService.get(key);
        ActivityAppResponse activityAppResponse;
        if (StringUtils.isEmpty(s)) {
            activityAppResponse = activityService.getActivityListApp();
            redisService.set(key, JSON.toJSONString(activityAppResponse));
            redisService.expire(key, ExpireTimeConstant.OLDFORNEW_PAGE);
        } else {
            activityAppResponse = JSONObject.parseObject(s, ActivityAppResponse.class);
        }
        // 用户积分
        UsersResponse h5CurrentUser = this.getH5CurrentUser();
        if (h5CurrentUser == null) {
            activityAppResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        } else {
            activityAppResponse.setScore(h5CurrentUser.getScore());
        }
        // 用户红包
//        UsersResponse usersResponse = this.getUsersActivityMax();
        ReturnCouponResponse returnCouponResponse = this.getReturnCoupon();
        activityAppResponse.setActivityMax(returnCouponResponse.getActivityMax());

        return CommonResult.success(activityAppResponse);
    }

    /**
     * 根据栏目id获取年货列表 h5
     *
     * @return
     */
    @GetMapping("/getNewYearGoods")
    public CommonResult getNewYearGoods(@RequestParam(value = "type") Integer type) {
        NewYearGoodsResponse response = activityService.getNewYearGoods(type);
        return CommonResult.success(response);
    }

    private UsersResponse getUsersActivityMax() {
        String token;
        UsersResponse usersResponse = new UsersResponse();
        if ("h5".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        if (StringUtils.isNotEmpty(token) && StringUtils.isNotEmpty(redisService.get(token))) {
            usersResponse = JSONObject.parseObject(redisService.get(token), UsersResponse.class);
            usersResponse.setActivityMax(Optional.ofNullable(usersResponse.getActivityMax()).orElse(new BigDecimal(680)));
            redisService.set(token, com.gexin.fastjson.JSON.toJSONString(usersResponse));
        }
        return usersResponse;
    }

    /**
     * 获取红包返现专区商品列表
     *
     * @return
     */
    @GetMapping("/getReturnCouponSpecial")
    public CommonResult getReturnCouponSpecial() {
        UsersResponse h5CurrentUser = this.getH5CurrentUser();
        return CommonResult.success(activityService.getReturnCouponSpecial(h5CurrentUser));
    }


    /**
     * 品牌补贴,点击品牌后,进入的内页
     *
     * @return
     */
    @GetMapping("/getProductsByBrandType")
    public CommonResult getProductsByBrandType(@RequestParam(value = "type") String type) {
        return CommonResult.success(activityService.getProductsByBrandType(type));
    }

    /**
     * 品牌补贴,外页
     *
     * @return
     */
    @GetMapping("/getBrandList")
    public CommonResult getBrandList() {
        return CommonResult.success(activityService.getBrandList());
    }

    /**
     * 爆品下载页
     *
     * @return
     */
    @GetMapping("/getHotProductDownload")
    public CommonResult getHotProductDownload(@RequestParam(value = "productId") Integer productId) {
        return CommonResult.success(activityService.getHotProductDownload(productId));
    }

    /**
     * @Description 获取积分兑好礼超值兑商品列表
     *
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/getCashScoreProductList")
    public CommonResult getCashScoreProductList(@RequestParam("pageSize") Integer pageSize,
                                                @RequestParam("pageNum") Integer pageNum) {
        return CommonResult.page(activityService.getCashScoreProductList(pageSize, pageNum));

    }


    /**
     * 查询积分栏目集合
     */
    @GetMapping("/queryCashScoreColumnH5")
    public CommonResult queryCashScoreColumnH5() {
        Map<String,Object> result = activityService.queryCashScoreColumnH5();
//        if(!"h5".equals(TokenUtil.getSource())){
//            result.put("score",this.getH5CurrentUser().getScore());
//        }
        return CommonResult.success(result);
    }

    /**
     * 根据积分栏目查询上铺列表
     */
    @GetMapping("/queryCashScoreListH5")
    public CommonResult queryCashScoreListH5(@RequestParam(value = "columnId", required = false) Integer columnId,
                                             @RequestParam(value = "pageSize") Integer pageSize,
                                             @RequestParam(value = "pageNum") Integer pageNum,
                                             @RequestParam(value = "flag", required = false) Integer flag,
                                             @RequestParam(value = "unionFlag", required = false) Integer unionFlag,
                                             @RequestParam(value = "consumerPower",defaultValue = "",required = false) String consumerPower) {
        log.info("===unionFlag==={}", unionFlag);
        List<ProductShortResponse> result = activityService.queryCashScoreListH5(columnId,pageSize,pageNum,flag,consumerPower, unionFlag);
        return CommonResult.success(result);
    }

    /**
     * 以旧换新列表
     *
     * @return
     */
    @GetMapping("/queryOldForNewListByPage")
    public CommonResult queryOldForNewListByPage(@RequestParam(value = "columnId") Integer columnId,
                                                 @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize,
                                                 @RequestParam(value = "pageNum", required = false, defaultValue = "20") Integer pageNum,
                                                 @RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag,
                                                 @RequestParam(value = "activityMax", required = false) BigDecimal activityMax) {

//        String key = com.ytjj.qmyx.mall.constants.RedisConstants.EXTENSION + "oldForNew" + columnId + "_ByPage_" + pageNum + pageSize;
//        String s = redisService.get(key);
        List<OldForNewProductDto> productList = null;
//        if (s != null) {
//            productList = JSONArray.parseArray(s, OldForNewProductDto.class);
//        } else {
        productList = activityService.queryOldForNewList(columnId, pageNum, pageSize,flag, activityMax);
//            redisService.set(key, JSON.toJSONString(productList));
//            redisService.expire(key, ExpireTimeConstant.OLDFORNEW_PAGE);
//        }

        String subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
        String token = TokenUtil.getToken();

        productList = productList.stream()
                .map(i -> {
                    Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                    if (subsidyHash != null && subsidyHash.size() > 0) {
                        Object subsidyData = subsidyHash.get(i.getId().toString());
                        if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                            i.setIsReceiveSubsidy(1);
                        }else {
                            i.setIsReceiveSubsidy(0);
                        }
                    }
                    return i;
                })
                .collect(Collectors.toList());
        return CommonResult.success(productList);
    }
    /**
     * 以旧换新列表
     * 同时返回补贴领取信息
     * @return
     */
    @GetMapping("/queryOldForNewListAndInfoByPage")
    public CommonResult queryOldForNewListAndInfoByPage(@RequestParam(value = "columnId") Integer columnId,
                                                        @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize,
                                                        @RequestParam(value = "pageNum", required = false, defaultValue = "20") Integer pageNum,
                                                        @RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
        List<OldForNewProductDto> productList = null;
        productList = activityService.queryOldForNewList(columnId, pageNum, pageSize,flag);

        String subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
        String token = TokenUtil.getToken();

        productList = productList.stream()
                .map(i -> {
                    Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                    if (subsidyHash != null && subsidyHash.size() > 0) {
                        Object subsidyData = subsidyHash.get(i.getId().toString());
                        if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                            i.setIsReceiveSubsidy(1);
                        }else {
                            i.setIsReceiveSubsidy(0);
                        }
                    }
                    return i;
                })
                .collect(Collectors.toList());
        Map resultMap=new HashMap();
        resultMap.put("productList",productList);
        resultMap.put("subsidyInfo",activityService.getUserSubsidyInfo());
        return CommonResult.success(resultMap);
    }
    /**
     * 新H5以旧换新首页
     */
    @GetMapping("/oldForNewIndex")
    public CommonResult oldForNewIndex(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
        return CommonResult.success(activityService.getOldForNewIndex(flag));
    }
    /**
     * 获取会员中心数据
     */
    @GetMapping("/getVipCenterProduct")
    public CommonResult getVipCenterProduct() {
        return CommonResult.success(activityService.getVipCenterProduct());
    }

    @GetMapping("/getFakeUserList")
    public CommonResult getFakeUserList(@RequestParam(value="activityType",required = false,defaultValue = "") String activityType) {
        // 假用户
        List<Object> fakeUserList = redisService.range(com.ytjj.qmyx.mall.constants.RedisConstants.FAKE_USER, 0, -1);
        StringBuilder fakeUserActivityProductKey = new StringBuilder("fake:user:productList:").append(activityType) ;
        String fakeUserActivityProductListStr = redisService.get(fakeUserActivityProductKey.toString());
        List<Product> productList = new ArrayList<>();
        if (StringUtils.isNotEmpty(fakeUserActivityProductListStr)) {
            productList= JSONObject.parseArray(fakeUserActivityProductListStr, Product.class);
        }else {
            productList=activityService.getProductByActivityType(activityType,20);
            redisService.set(fakeUserActivityProductKey.toString(), JSONObject.toJSONString(productList));
            redisService.expire(fakeUserActivityProductKey.toString(), 120);
        }

        Collections.shuffle(fakeUserList);
        List<UserFakeResponse> usersList = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .limit(productList.size())
                .map(UserFakeResponse::new)
                .collect(Collectors.toList());
        try {
            for (int i = 0; i < usersList.size(); i++) {
                Product product = productList.get(i);
                usersList.get(i).setProductId(product.getProductId());
                usersList.get(i).setProductName(product.getProductName());
                usersList.get(i).setProductImg(product.getProductImg());
                usersList.get(i).setMoney(product.getActivityMax());
            }
        }catch (Exception e){
            log.error("处理虚拟用户购买错误");
        }
        return CommonResult.success(usersList);
    }

    @PostMapping("/newUserDeliveryAddress")
    public CommonResult newUserDeliveryAddress(@RequestBody NewExclusiveResponse newExclusiveResponse) {
        UsersResponse currentUser = getCurrentUser();
        newExclusiveResponse.setUserId(currentUser.getId());
        int i = activityService.newUserDeliveryAddress(newExclusiveResponse);
        if (i > 0) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 根据活动类型获取类型下的栏目
     * @param activityType 活动类型
     * @param isShow 是否显示 0.不显示 1.显示
     * @return
     */
    @GetMapping("/getColumn")
    public CommonResult getColumn(@RequestParam String activityType,@RequestParam(required = false) Integer isShow){
        return activityService.getColumn(activityType,isShow);
    }
}
